<template>
    <div>
      <el-container>
        <el-header>
          <h1>Video List</h1>
        </el-header>
        <el-main>
          <el-button @click="fetchVideos">Load Videos</el-button>
          <el-table :data="videos" style="width: 100%" v-if="videos.length">
            <el-table-column prop="id" label="序号" width="100"></el-table-column>
            <el-table-column prop="name" label="Video Name"></el-table-column>
            <el-table-column label="Actions">
              <template #default="scope">
                <el-button @click="playVideo(scope.row.id)">Play</el-button>
              </template>
            </el-table-column>
          </el-table>
          <p v-else>No videos available.</p>
        </el-main>
      </el-container>
    </div>
  </template>
  
  <script setup>
  import { ref } from 'vue';
  import { ElMessage } from 'element-plus';
  
  const videos = ref([]);
  
  const fetchVideos = async () => {
    try {
      const response = await fetch('http://192.168.0.40:5000/list_videos');
      if (!response.ok) {
        throw new Error('Network response was not ok');
      }
      videos.value = await response.json();
    } catch (error) {
      ElMessage.error('Failed to fetch videos');
      console.error(error);
    }
  };
  
  const playVideo = async (id) => {
    try {
      const response = await fetch(`http://192.168.0.40:5000/play_video?id=${id}`);
      if (!response.ok) {
        throw new Error('Failed to fetch video');
      }
      const videoBlob = await response.blob();
      const videoUrl = URL.createObjectURL(videoBlob);
  
      // 创建一个临时视频元素来播放
      const video = document.createElement('video');
      video.src = videoUrl;
      video.controls = true;
      video.width = '100%';
  
      // 清除之前的视频元素
      const oldVideo = document.querySelector('video');
      if (oldVideo) {
        oldVideo.remove();
      }
  
      document.body.appendChild(video);
    } catch (error) {
      ElMessage.error('Failed to play video');
      console.error(error);
    }
  };
  </script>